<?php 
require_once (dirname(__FILE__).'/services.php');
function dictionary_list($matches) {
	global $mvc;
    global $dictionaries, $pageNav, $count;
	$page = $matches[2] ? $matches[2] : 1;
    $size = 20;
	$count = service_dictionary_getCount();
	$pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."dictionary/list/page/#{page}/");
    $dictionaries = service_dictionary_getAll(($page - 1) * $size, $size);
	
	Utils::changeUserSerialToName($dictionaries, 'creator');
	
	foreach($dictionaries as &$dictionary) {
		$dictionary['term_num'] = service_dictionary_getTermsCount($dictionary['serial']);
	}
	
	$GLOBALS['message'] = $mvc->getMessage('message');
	$mvc->render(dirname(__FILE__)."/views/_dictionary_list_.php");
}
function dictionary_new($matches) {
	global $mvc;
	$method = $_SERVER['REQUEST_METHOD'];
    if ($method == 'GET') {
        $GLOBALS['message'] = $mvc->getMessage('message');
        $mvc->render(dirname(__FILE__).'/views/_dictionary_new_.php');
    } elseif ($method == 'POST') {
        global $title, $description, $error;
		$title = trim($_POST['title']);
		$description = trim($_POST['description']);
		
		if($title == "") $error['title'] = "Title is required.";
		
        if (count($error) > 0) {
            $mvc->render(dirname(__FILE__).'/views/_dictionary_new_.php');
            return;
        }
		global $currentUser;
		
		$serial = service_dictionary_create(array('title'=>$title, 'description'=>$description, 'creator'=>$currentUser['serial']));
        $mvc->setMessage('message', 'Dictionary created.');
        $mvc->redirect(REQUEST_BASE.'dictionary/'.$serial.'/show/');
    }
}
function dictionary_show($matches){
	global $mvc, $featureManager;
	global $dictionary, $terms, $pageNav, $category, $count, $source_all_abbrs, $isEditor;
	$serial = $matches[1];
	$dictionary = service_dictionary_getBySerial($serial);
	$dictionary['term_num'] = service_dictionary_getTermsCount($serial);
	
	$category = $matches[3] ? $matches[3] : "";
	
	$page = $matches[5] ? $matches[5] : 1;
    $size = 20;
	$count = service_dictionary_getTermsCount($serial, $category);
	$pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."dictionary/".$serial."/show/".$matches[2]."page/#{page}/");
	
	$isEditor = Utils::hasRight('dictionary.edit');
	
	$terms = service_dictionary_getTerms($serial, $category, $isEditor, ($page - 1) * $size, $size);
	
	$featureManager->apply("dictionary.get.source.name.by.serial", $source_all_names);
	$source_all_names = $source_all_names['sources'];
	foreach($source_all_names as $key=>$source) {
		$source_all_abbrs[$key] = $source['abbr']?$source['abbr']:$source['title'];
	}
	
	if($dictionary) {
		$GLOBALS['message'] = $mvc->getMessage('message');
        $mvc->render(dirname(__FILE__).'/views/_dictionary_show_.php');
	}
}
function dictionary_edit($matches) {
	global $mvc;
	global $title, $description, $serial;
	$method = $_SERVER['REQUEST_METHOD'];
	$serial = $matches[1];
    if ($method == 'GET') {
		$dictionary = service_dictionary_getBySerial($serial);
		
		$title = $dictionary['title'];
		$description = $dictionary['description'];
		
        $mvc->render(dirname(__FILE__).'/views/_dictionary_edit_.php');
    } elseif ($method == 'POST') {
        global $error;
		$title = trim($_POST['title']);
		$description = trim($_POST['description']);
		
		if($title == "") $error['title'] = "Title is required.";
		
        if (count($error) > 0) {
            $mvc->render(dirname(__FILE__).'/views/_dictionary_edit_.php');
            return;
        }
		global $currentUser;
		
		service_dictionary_update(array('serial'=>$serial, 'title'=>$title, 'description'=>$description, 'last_editor'=>$currentUser['serial']));
        $mvc->setMessage('message', 'Dictionary updated.');
        $mvc->redirect(REQUEST_BASE.'dictionary/'.$serial.'/show/');
    }
}
function dictionary_delete($matches) {
	global $mvc;
	$method = $_SERVER['REQUEST_METHOD'];
	if ($method == 'POST') {
		$serial = $_POST['serial'];
		service_dictionary_deleteBySerial($serial);
		$mvc->setMessage('message', 'Dictionary was dropped.');
        $mvc->redirect(REQUEST_BASE.'dictionary/');
	}
}
function dictionary_sources($matches) {
	global $mvc;
	global $serial;
	global $sources_imported;
	$serial = $matches[1];
	$method = $_SERVER['REQUEST_METHOD'];
	$sources_imported = service_dictionary_getSources($serial);
    if ($method == 'GET') {
		global $dictionary;
		global $sources;
		global $featureManager;
		$dictionary = service_dictionary_getBySerial($serial);
    	$dictionary['term_num'] = service_dictionary_getTermsCount($serial);
		
		$featureManager->apply("dictionary.get.all.glossaries", $sources);
		
    	$GLOBALS['message'] = $mvc->getMessage('message');
        $mvc->render(dirname(__FILE__).'/views/_dictionary_sources_.php');
    } elseif ($method == 'POST') {
		$sources_new = (array) $_POST['sources'];
		
		$sources_to_add = array();
		$sources_to_refresh = array();
		$sources_to_delete = array();
		
		$sources_all = array_unique(array_merge($sources_imported, $sources_new));
		foreach($sources_all as $source) {
			if(in_array($source, $sources_imported)) {
				if(in_array($source, $sources_new)) array_push($sources_to_refresh, $source);
				else array_push($sources_to_delete, $source);
			} else array_push($sources_to_add, $source);
		}
		
		$add = service_dictionary_addSources($serial, $sources_to_add);
		$delete_num = service_dictionary_deleteSources($serial, $sources_to_delete);
		$update_num = service_dictionary_refreshSources($serial, $sources_to_refresh);
		
		if($add['term']) $message .= $add['term']." terms added, ";
		if($add['definition']) $message .= $add['definition']." definition added, ";
		if($delete_num) $message .= "$delete_num definition deleted, ";
		
		$message = substr($message, 0, strlen($message) - 2);
		
        $mvc->setMessage('message', $message);
        $mvc->redirect(REQUEST_BASE.'dictionary/'.$serial.'/show/');
    }
}
function dictionary_definition_conflict_handle_ajax($matches) {
	$method = $_SERVER['REQUEST_METHOD'];
	if($method == "POST") {
		$serial = trim($_POST['serial']);
		$action = trim($_POST['action']);
		
		$result = "";
		if($action == "discard") {
			$result = service_dictionary_discardConflict($serial);
		} else if($action == "adopt") {
			$result = service_dictionary_adoptConflict($serial);
		}
		echo json_encode(array('action'=>$action, 'result'=>$result));
	}
}
function dictionary_deleteterm_ajax($matches) {
	$method = $_SERVER['REQUEST_METHOD'];
	if($method == "POST") {
		$serial = trim($_POST['serial']);
		global $currentUser;
		service_dictionary_deleteTermBySerial($serial);
		echo json_encode(array('result'=>1));
	}
}
function dictionary_merge_definition_ajax($matches) {
	$method = $_SERVER['REQUEST_METHOD'];
	if($method == "POST") {
		$from = trim($_POST['source']);
		$to = trim($_POST['target']);
		service_dictionary_merge_definition($from, $to);
		echo json_encode(array('result'=>1));
	}
}
function dictionary_split_definition_ajax($matches) {
	$method = $_SERVER['REQUEST_METHOD'];
	if($method == "POST") {
		global $featureManager;
		$source = trim($_POST['source']);
		$mergedto = trim($_POST['definition']);
		$definition = service_dictionary_split_definition($mergedto, $source);
		
		$conflict_definitions = service_dictionary_getConflictDefinition($definition['term']);
		
		$comefroms = explode(',', $definition['comefrom']);
		foreach($comefroms as $comefrom) {
			if (array_key_exists($comefrom, $conflict_definitions)) $definition['conflict_definition'] = array_merge((array)$definition['conflict_definition'], $conflict_definitions[$comefrom]);
		}
		
		$featureManager->apply("dictionary.get.source.name.by.serial", $source_all_names);
		$source_all_names = $source_all_names['sources'];
		foreach($source_all_names as $key=>$source) {
			$source_all_abbrs[$key] = $source['abbr']?$source['abbr']:$source['title'];
		}
		
		$GLOBALS['definition'] = $definition;
		$GLOBALS['source_all_abbrs'] = $source_all_abbrs;
		$html = Utils::loadSegment(dirname(__FILE__)."/views/segments/_s_dictionary_term_definition_.php");
		
		echo $html;
	}
}
function dictionary_sort_definition_ajax($matches) {
	$method = $_SERVER['REQUEST_METHOD'];
	if($method == "POST") {
		$orders = $_POST['order'];
		for($i = 0;$i < count($orders);$i++) {
			service_dictionary_definition_setorder($orders[$i], $i+1);
		}
		echo json_encode(array('result'=>$order));
	}
}
function dictionary_search($matches) {
	global $mvc, $featureManager;
    global $dictionary ,$pageNav, $count, $query, $terms, $source_all_abbrs;
    $page = $matches[4] ? $matches[4] : 1;
    
    $queryRaw = $matches[1];
    $query = urldecode(urldecode($matches[1]));
	$belongto = $matches[2];
    $size = 20;
    
    if (Utils::isBlank($query)) {
        $mvc->redirect(REQUEST_BASE."dictionary/");
    } else {
        $result = service_dictionary_term_search($query, $belongto, ($page - 1) * $size, $size);
        $terms = $result['terms'];
        $count = $result['count'];
        $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."dictionary/search/?query=".$queryRaw."&dictionary=".$belongto."&page=#{page}");
        
		$featureManager->apply("dictionary.get.source.name.by.serial", $source_all_names);
		$source_all_names = $source_all_names['sources'];
		foreach($source_all_names as $key=>$source) {
			$source_all_abbrs[$key] = $source['abbr']?$source['abbr']:$source['title'];
		}
		
		$dictionary = service_dictionary_getBySerial($belongto);
		$dictionary['term_num'] = service_dictionary_getTermsCount($dictionary['serial']);
		
		$mvc->render(dirname(__FILE__)."/views/_dictionary_search_.php");
    }
}
function dictionary_mydictionary($matches) {
	global $mvc;
    global $dictionaries, $count;
	global $currentUser;
    $dictionaries = service_dictionary_getByCreator($currentUser['serial']);
	if(count($dictionaries)) {
		foreach($dictionaries as &$dictionary) {
			$dictionary['term_num'] = service_dictionary_getTermsCount($dictionary['serial']);
		}
		Utils::changeUserSerialToName($dictionaries, 'creator');
	} else $dictionaries = array();
	$count = count($dictionaries);
	$GLOBALS['message'] = $mvc->getMessage('message');
	$mvc->render(dirname(__FILE__)."/views/_dictionary_mydictionary_.php");
}
global $mvc;
$mvc = new MVC(Array('{^/dictionary/$}'=>'dictionary_list',
	 '{^/dictionary/list/(page/([0-9]+)\/)?$}'=>'dictionary_list',
	 '{^/dictionary/mydictionary/$}'=>'dictionary_mydictionary',
     '{^/dictionary/new/$}'=>'dictionary_new',
	 '{^/dictionary/([^/]+)/show/(category/([\w])\/)?(page/([0-9]+)\/)?$}'=>'dictionary_show',
	 '{^/dictionary/([^/]+)/edit/$}'=>'dictionary_edit',
	 '{^/dictionary/delete/$}'=>'dictionary_delete',
	 '{^/dictionary/search/\?query=([^\&]*)\&dictionary=([^\&]*)(\&page=([0-9]+))?}'=>'dictionary_search',
	 '{^/dictionary/([^/]+)/sources/$}'=>'dictionary_sources',
	 '{^/dictionary/conflict/$}'=>'dictionary_definition_conflict_handle_ajax',
	 '{^/dictionary/deleteterm/$}'=>'dictionary_deleteterm_ajax',
	 '{^/dictionary/definition/merge/$}'=>'dictionary_merge_definition_ajax',
	 '{^/dictionary/definition/split/$}'=>'dictionary_split_definition_ajax',
	 '{^/dictionary/definition/sort/$}'=>'dictionary_sort_definition_ajax',
     ));
$mvc->dispatch($GLOBALS['uri']);

?>
